package com.gl.util.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import com.gl.util.CommonUtil;

public class HttpClientUtil {
	/**
	 * 使用http方式发送请求 返回请求报文
	 * @Title: request  
	 * @Discription:   
	 * @param urlString
	 * @param param
	 * @return
	 * @throws IOException 
	 * @return String  
	 * 
	 * 修改历史
	 * --------------------------------------- 
	 * lvbo 2014-6-10 下午08:17:09
	 */
	public static String request(String urlString, String charset, String param, String contentType) throws IOException {
		URL url = new URL(urlString);
		URLConnection connection = url.openConnection();
		connection.setConnectTimeout(30000);
		connection.setReadTimeout(30000); 
		if(CommonUtil.notEmpty(contentType)) {
			connection.setRequestProperty("Content-Type", "text/xml");
		}
		addInputParam(connection, charset, param); // 添加请求参数
		
		InputStream inputStream = connection.getInputStream();
		
//		byte[] b = new byte[1024 * 10];
//		int len;
//		BufferedInputStream bis = new BufferedInputStream(inputStream);
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset));
		StringBuffer buffer = new StringBuffer();
		String line = null;
		
		while((line = br.readLine()) != null) {
			buffer.append(line);
		}
		
//		bis.close();
		br.close();
		inputStream.close();
		
		return buffer.toString();
	}
	
	
	/**
	 * 为请求添加请求参数
	 * @Title: addInputParam  
	 * @Discription:   
	 * @param connection
	 * @param request
	 * @throws IOException 
	 * @return void  
	 * 
	 * 修改历史
	 * --------------------------------------- 
	 * lvbo 2014-6-10 下午08:16:48
	 */
	private static void addInputParam(URLConnection connection, String charset, String request) throws IOException {
		connection.setDoOutput(true);
		
		// 此处getOutputStream会隐含的进行connect(即：如同调用上面的connect()方法， 
		// 所以在开发中不调用上述的connect()也可以)。 
		OutputStream outStrm = connection.getOutputStream(); 
		
		// 向对象输出流写出数据，这些数据将存到内存缓冲区中 
		byte[]  bytes = CommonUtil.empty(charset) ? request.getBytes() : request.getBytes(charset);
		outStrm.write(bytes);

		// 刷新对象输出流，将任何字节都写入潜在的流中
		outStrm.flush(); 

		// 关闭流对象。此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中, 
		// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 
		outStrm.close();
	}
}